<!--
 * @Author: Olivia
 * @Date: 2022-06-12 22:28:17
 * @LastEditTime: 2022-06-23 23:13:21
 * @FilePath: \toutiao-m\src\views\home\components\article-list.vue
 * @custom_string_Olivia: Less is more
-->
<template>
  <div class="article-list">
    <van-pull-refresh
      :success-duration="1500"
      v-model="isLoading"
      @refresh="onRefresh"
      :success-text="successText"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
      <article-item
      v-for="(article, index) in list"
          :key="index"
          :article="article"
      />
        <!-- <van-cell
          v-for="(article, index) in list"
          :key="index"
          :title="article.title"
        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { getArticleList } from '../../../api/article'
import ArticleItem from '@/components/articleItem'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isLoading: false,
      successText: ''
    }
  },
  created () {},
  computed: {},
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getArticleList({
          channel_id: this.item.id,
          timestamp: this.timestamp || Date.now(), // 时间戳，请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳
          with_top: 1 // 是否包含置顶，进入页面第一次请求时要包含置顶文章，1-包含置顶，0-不包含
        })
        // if (Math.random() > 0.5) {
        //   JSON.parse('hshshshshs')
        // }
        const { results } = data.data
        // this.list = this.list.concat(results)
        this.list.push(...results)
        this.loading = false
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (error) {
        this.error = true
        this.loading = false
        console.log(error)
      }
    },
    async onRefresh () {
      try {
        const { data } = await getArticleList({
          channel_id: this.item.id,
          timestamp: Date.now(),
          with_top: 1
        })

        const { results } = data.data
        this.list.unshift(...results)
        this.isLoading = false
        this.successText = `下拉刷新${results.length}条成功`
      } catch (error) {
        this.successText = '下拉刷新失败'
        this.isLoading = false
      }
    }
  }
}
</script>
<style lang="less">
.article-list {
  padding-bottom: 46px;
}
</style>
